package com.mauth.web.controller;

import com.mauth.common.dto.auth.ClientParameter;
import com.mauth.common.dto.auth.LoginInfo;
import com.mauth.common.entity.user.User;
import com.mauth.web.service.AuthService;
import com.mauth.web.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Resource
    private AuthService authService;
    @Value("${system.auth-server-url}")
    private String authUrl;

    @Resource
    private UserService userService;

    @GetMapping("")
    public String loginPage() {
        return "login";
    }

    @PostMapping("")
    public void login(String userName, String password,
                      HttpSession session,
                      HttpServletResponse response) throws IOException {
        String uri = authUrl;
        User dbUser = validUser(userName, password);
        ClientParameter param = authService.getOauth2Parameter(session);
        if (dbUser != null && param != null) {
            uri += "/oauth2/authorize";
            uri = uri + param;
            LoginInfo loginInfo = LoginInfo.builder()
                    .userName(dbUser.getUserName())
                    .loginTime(LocalDateTime.now())
                    .clientId(Integer.parseInt(param.getClient_id()))
                    .userSeq(dbUser.getUserSeq())
                    .build();
            session.setAttribute("loginInfo", loginInfo);
        } else {
            uri += "/login";
        }
        String redirectUrl = response.encodeRedirectURL(uri);
        response.sendRedirect(redirectUrl);
    }

    private User validUser(String userName, String password) {
        User dbUser = userService.getUserByName(userName);
        if (dbUser != null && checkUserPassword(dbUser, password)) {
            return dbUser;
        }
        return null;
    }

    private boolean checkUserPassword(User user, String password) {
        return user.getPassword().equals(password);
    }
}
